#!/bin/bash

#plist文件管理
PlistBuddy='/usr/libexec/PlistBuddy'
readonly PlistBuddy

#证书管理
Security='/usr/bin/security'
readonly Security

#签名管理
codesign='/usr/bin/codesign'
readonly codesign

#IPA中Info.plist文件路径
ipaPlist='Payload/*.app/Info.plist'
readonly ipaPlist

#ipa资源路径
ipaPath='.'
readonly ipaPath

#plist文件开头
plistPrefix='<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict/></plist>'
readonly plistPrefix

# *.mobileprovision
mobileprovisionPlist='mobileprovision.plist'
readonly mobileprovisionPlist

# entitlements.plist
entitlementsPlist='entitlements.plist'
readonly entitlementsPlist

#判断需要解压
if [[ -e Payload ]]; then
	#statements
	echo Payload
else
	#获取当前目录ipa文件
	echo 'ipa包列表:'
	i=0
	for file in $(ls $ipaPath/*.ipa); do
		i=`expr $i + 1`
		file=${file##*/}
		file=${file%.*}
		echo "[$i].$file"
	done

	if [[ $i -gt 1 ]]; then
		read -p '输入你要操作的ipa包名:' ipaName
	elif [[ $i -eq 1 ]]; then
		ipaName=$file
	else
		echo '[错误]:没有找到ipa文件'
		exit
	fi

	if [[ -e $ipaPath/${ipaName}.ipa ]]; then
		#解压ipa包
		unzip $ipaPath/${ipaName}.ipa
		#删除__MACOSX垃圾文件
		rm -rf __MACOSX
	else
		echo '[错误]:没有找到您要操作的ipa包'
		exit
	fi
fi


#获取当前目录的证书文件
echo '打包描述文件列表:'
i=0
for file in $(ls ./*.mobileprovision); do
	i=`expr $i + 1`
	file=${file#./}
	file=${file%.*}
	echo "[$i].$file"
done

if [[ $i -gt 1 ]]; then
	read -p '输入你要操作的证书名:' mobileprovisionFile
elif [[ $i -eq 1 ]]; then
	mobileprovisionFile=$file
else
	echo '[错误]:没有找到描述文件'
fi

if [[ $mobileprovisionFile ]]; then
	
	#导出证书描述信息到plist
	echo $plistPrefix > $mobileprovisionPlist
	`security cms -D -i ${mobileprovisionFile}.mobileprovision > ${mobileprovisionPlist}`

	#导出打包参数
	echo $plistPrefix > $entitlementsPlist
	`$PlistBuddy -x -c "Print :Entitlements" $mobileprovisionPlist > $entitlementsPlist`

	#获取 TeamID
	TeamID=$($PlistBuddy -c "Print :com.apple.developer.team-identifier" $entitlementsPlist)
	#获取 包名信息
	BundelID=$($PlistBuddy -c "Print :CFBundleIdentifier" $ipaPlist)
	#配置 application-identifier
	$PlistBuddy -c "Set :application-identifier ${TeamID}.${BundelID}" $entitlementsPlist

	#配置 keychain-access-groups
	for (( i = 0; i < 9; i++ )); do
		read -p '添加渠道要求[keychain-access-groups],直接回车退出:' keychain_access_groups
		if [[ -n $keychain_access_groups ]]; then
				$PlistBuddy -c "Add :keychain-access-groups:$i string ${TeamID}.$keychain_access_groups" $entitlementsPlist
			else
				break
			fi
	done

	#根据teamID搜索钥匙串信息
	certificates=$($Security find-identity -v -p codesigning | grep $TeamID)
	cerNumber=${#certificates[*]}
	echo "匹配[${TeamID}]钥匙串信息个数: $cerNumber"

	if [[ $cerNumber -eq 1 ]]; then
		#取出证书
		keySign=${certificates[0]}
		keySign=${keySign#*)}
		#截取校验值
		# 075FF93C13 4EDDD0C310 75BE6F7993 BF8842DD85
		# keySign=${keySign::41} 
		#截取开发者信息
		keySign=${keySign#*\"}
		keySign=${keySign%\"*}

		echo $keySign
	else
		echo "钥匙串证书异常,请添加对应证书或删除无关的证书"
		exit
	fi

	#开始签名操作
	#通过Info.plist获取ipa包名称
	CFBundleExecutable=$($PlistBuddy -c "Print :CFBundleExecutable" $ipaPlist)
	echo "准备签名:${CFBundleExecutable}.app"

	rm -rf Payload/${CFBundleExecutable}.app/_CodeSignature/

	#复制到描述文件到ipa包
	cp ${mobileprovisionFile}.mobileprovision Payload/${CFBundleExecutable}.app/embedded.mobileprovision

	#签名framework
	for file in ./Payload/${CFBundleExecutable}.app/Frameworks/*.framework; do
		framwork=${file##*/}
		resignFwork=${framwork%.*}
		echo ${resignFwork}.framework

		$codesign -f -s "$keySign" Payload/${CFBundleExecutable}.app/Frameworks/${resignFwork}.framework/${resignFwork}
	done

	#签名swift库
	for file in ./Payload/${CFBundleExecutable}.app/Frameworks/*.dylib; do
		dylib=${file##*/}
		resignDylib=${dylib%.*}
		echo ${resignDylib}.dylib
		$codesign -f -s "$keySign" Payload/${CFBundleExecutable}.app/Frameworks/${resignDylib}.dylib
	done

	#签名app
	$codesign -f -s "$keySign" --entitlements $entitlementsPlist Payload/${CFBundleExecutable}.app

	#打包命名
	read -p '请输入渠道商名称:' inputChannelName

	CFBundleDisplayName=$($PlistBuddy -c "Print :CFBundleDisplayName" $ipaPlist)
	CFBundleShortVersionString=$($PlistBuddy -c "Print :CFBundleShortVersionString" $ipaPlist)
	CFBundleVersion=$($PlistBuddy -c "Print :CFBundleVersion" $ipaPlist)

	#判断是否为Dis
	beta_reports_active=$($PlistBuddy -c "Print :beta-reports-active" $entitlementsPlist)
	if [[ $beta_reports_active ]]; then
		beta='Dis'
	else
		beta='Hoc'
	fi

	if [[ -z $inputChannelName ]];then
		newIpaName="${CFBundleDisplayName}_${CFBundleShortVersionString}(${CFBundleVersion})_${beta}"
	else
		newIpaName="${inputChannelName}_${CFBundleDisplayName}_${CFBundleShortVersionString}(${CFBundleVersion})_${beta}"
	fi
	

	echo "生成ipa名字: $newIpaName"

	#压缩ipa包
	zip -r "${newIpaName}.ipa" Payload/

	#清除垃圾文件
	rm -rf $mobileprovisionPlist
	# rm -rf $entitlementsPlist

fi
